<?php
require '../db.php';
if (!isset($_SESSION['user_id']) || $_SESSION['role'] !== 'admin') {
    header("Location: ../login.php");
    exit;
}

$settings = file_exists(__DIR__ . '/../settings.json') ? json_decode(file_get_contents(__DIR__ . '/../settings.json'), true) : ['title' => '私人网盘'];
$site_title = $settings['title'];

if (isset($_GET['delete'])) {
    $stmt = $conn->prepare("DELETE FROM users WHERE id = ?");
    $stmt->bind_param("i", $_GET['delete']);
    $stmt->execute();
    header("Location: users.php");
    exit;
}

$result = $conn->query("SELECT id, username, role FROM users");

if (isset($_GET['edit'])) {
    $edit_id = (int)$_GET['edit'];
    $stmt = $conn->prepare("SELECT username, role FROM users WHERE id = ?");
    $stmt->bind_param("i", $edit_id);
    $stmt->execute();
    $user = $stmt->get_result()->fetch_assoc();

    if ($_SERVER['REQUEST_METHOD'] == 'POST') {
        $username = $_POST['username'];
        $role = $_POST['role'];
        $password = !empty($_POST['password']) ? password_hash($_POST['password'], PASSWORD_DEFAULT) : $user['password'];
        if (strlen($username) > 191) {
            echo "<script>alert('用户名不能超过191个字符！'); history.back();</script>";
            exit;
        }
        $stmt = $conn->prepare("UPDATE users SET username = ?, role = ?, password = ? WHERE id = ?");
        $stmt->bind_param("sssi", $username, $role, $password, $edit_id);
        $stmt->execute();
        header("Location: users.php");
        exit;
    }
}
?>

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>用户管理</title>
    <link href="/assets/bootstrap/css/bootstrap.min.css" rel="stylesheet">
</head>
<body class="<?= $settings['theme'] === 'dark' ? 'bg-dark text-white' : '' ?>">
    <nav class="navbar navbar-expand-lg <?= $settings['theme'] === 'dark' ? 'navbar-dark bg-dark' : 'navbar-light bg-light' ?>">
        <div class="container">
            <a class="navbar-brand" href="index.php">后台管理</a>
            <div class="collapse navbar-collapse">
                <ul class="navbar-nav ms-auto">
                    <li class="nav-item"><a class="nav-link" href="../index.php">网站前台</a></li>
                    <li class="nav-item"><a class="nav-link" href="users.php">用户管理</a></li>
                    <li class="nav-item"><a class="nav-link" href="files.php">文件管理</a></li>
                    <li class="nav-item"><a class="nav-link" href="categories.php">分类管理</a></li>
                    <li class="nav-item"><a class="nav-link" href="settings.php">网站设置</a></li>
                    <li class="nav-item"><a class="nav-link" href="../logout.php">退出</a></li>
                </ul>
            </div>
        </div>
    </nav>
    <div class="container py-5">
        <h2>用户管理</h2>
        <table class="table table-striped">
            <thead>
                <tr>
                    <th>ID</th>
                    <th>用户名</th>
                    <th>角色</th>
                    <th>操作</th>
                </tr>
            </thead>
            <tbody>
                <?php while ($user = $result->fetch_assoc()): ?>
                    <tr>
                        <td><?= $user['id'] ?></td>
                        <td><?= htmlspecialchars($user['username']) ?></td>
                        <td><?= $user['role'] ?></td>
                        <td>
                            <a href="users.php?edit=<?= $user['id'] ?>" class="btn btn-warning btn-sm">编辑</a>
                            <a href="users.php?delete=<?= $user['id'] ?>" class="btn btn-danger btn-sm" onclick="return confirm('确认删除？')">删除</a>
                        </td>
                    </tr>
                <?php endwhile; ?>
            </tbody>
        </table>

        <?php if (isset($_GET['edit'])): ?>
            <h3>编辑用户</h3>
            <form method="POST">
                <div class="mb-3">
                    <label for="username" class="form-label">用户名</label>
                    <input type="text" class="form-control" id="username" name="username" value="<?= htmlspecialchars($user['username']) ?>" maxlength="191" required>
                </div>
                <div class="mb-3">
                    <label for="role" class="form-label">角色</label>
                    <select class="form-select" id="role" name="role">
                        <option value="user" <?= $user['role'] == 'user' ? 'selected' : '' ?>>普通用户</option>
                        <option value="admin" <?= $user['role'] == 'admin' ? 'selected' : '' ?>>管理员</option>
                    </select>
                </div>
                <div class="mb-3">
                    <label for="password" class="form-label">新密码（留空不修改）</label>
                    <input type="password" class="form-control" id="password" name="password">
                </div>
                <button type="submit" class="btn btn-primary">保存</button>
            </form>
        <?php endif; ?>
    </div>
    <script src="/assets/bootstrap/js/bootstrap.bundle.min.js"></script>
</body>
</html>